/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import java.security.spec.PSSParameterSpec;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.CorMODEL;

/**
 *
 * @author Welisson
 */
public class CorDAO extends GenericDAO {
    private static final String INSERT = "INSERT INTO cores( cor_cores) VALUES ( ?);";
    private static final String UPDATE = "UPDATE cores SET cor_cores=? WHERE cor_id = ?;";
    private static final String DELETE = "DELETE FROM cores WHERE cor_id = ?;";
    private static final String SELECT = "SELECT * FROM cores ORDER BY cor_cores ASC;";
    
    public int insert(CorMODEL cor) throws SQLException{
        
        PreparedStatement ps = conn.prepareStatement(INSERT, PreparedStatement.RETURN_GENERATED_KEYS);
        int id = -1;
        ResultSet rs;
        ps.setString(1, cor.getCor());
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        
        while(rs.next()){
            id = rs.getInt(1);
        }
        
        rs.close();
        ps.close();
        conn.close();
        return id;
    }
    
    public boolean update(CorMODEL cor) {
        
        PreparedStatement ps;
        try {
            ps = conn.prepareStatement(UPDATE);
            ps.setString(1, cor.getCor());
            ps.setInt(2, cor.getId());
            ps.execute();
            
            ps.close();
            conn.close();
            return true;
        } catch (SQLException ex) {
            ex.printStackTrace(System.out);
            return false;
        }
        
    }
    
    public boolean delete(int id){
        
        PreparedStatement ps;
        try {
            ps = conn.prepareStatement(DELETE);
            ps.setInt(1, id);
            ps.execute();
            
            ps.close();
            conn.close();
            return true;
        } catch (SQLException ex) {
            ex.printStackTrace(System.out);
            return false;
        }
        
    }
    
    public List<CorMODEL> findCores() throws SQLException{
        PreparedStatement ps = conn.prepareStatement(SELECT);
        ResultSet rs = ps.executeQuery();
        List<CorMODEL> cores = new ArrayList<>();
        
        while(rs.next()){
            CorMODEL cor = new CorMODEL();
            cor.setId(rs.getInt("cor_id"));
            cor.setCor(rs.getString("cor_cores"));
            cores.add(cor);
        }
        
        ps.close();
        rs.close();
        conn.close();
        
        return cores;
        
    }
    
}
